#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: liang kang
@contact: gangkanli1219@gmail.com
@time: 2018/3/9 21:15
@desc: 
"""
import os

import numpy as np


def num_samples(x):
    """
    返回类似数组的数据数量

    Parameters
    ----------
    x: array-like

    Returns
    -------

    """
    if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
        if hasattr(x, '__array__'):
            x = np.asarray(x)
        else:
            raise TypeError("Expected sequence or array-like, got %s" %
                            type(x))
    if hasattr(x, 'shape'):
        if len(x.shape) == 0:
            raise TypeError("Singleton array %r cannot be considered"
                            " a valid collection." % x)
        return x.shape[0]
    else:
        return len(x)


def check_consistent_length(*arrays):
    """
    检查所有数组的第一维的长度是否相等

    Parameters
    ----------
    *arrays : list or tuple of input objects.
        Objects that will be checked for consistent length.
    """
    lengths = [num_samples(X) for X in arrays if X is not None]
    uniques = np.unique(lengths)
    if len(uniques) > 1:
        raise ValueError("Found input variables with inconsistent numbers of"
                         " samples: %r" % [int(l) for l in lengths])


def merge_dict(*dicts):
    """
    合并一系列字典，合并后的字典的key是所有字典的key的并集，
    其value取和

    Parameters
    ----------
    dicts: 字典列表

    Returns
    -------
    合并后的字典
    """
    res = {}
    for _dict in dicts:
        for key, value in _dict.items():
            if key not in res:
                res[key] = value
            else:
                res[key] += value
    return res


def get_name_and_ext(file_name):
    """
    获取文件名，包含扩展名

    Parameters
    ----------
    file_name: 文件完整路径

    Returns
    -------

    """
    (_, temp_filename) = os.path.split(file_name)
    (shot_name, extension) = os.path.splitext(temp_filename)
    return shot_name, extension
